import json
import logging
from google.appengine.api import urlfetch
import urllib
class PSUtils():
	str_ps2Char_url = "http://census.soe.com/get/ps2-beta/character/"
	str_ps2Outfit_url = "http://census.soe.com/get/ps2-beta/outfit/"
	str_ps2OutfitMem_url = "http://census.soe.com/get/ps2-beta/outfit_member/"

	str_outfitName = "PC Gamer"
	#request info to send to the outfit url
	dict_outfitFields = {"name":str_outfitName,"c:resolve":"member","c:resolve":"member_character(name)"}
	#list to hold the members returned
	lst_members = []

	#Connect to the outfit site and collect all of the names of the people in the outfit. 
	#Then send these names to the character site, and retrieve the killed_by information. 
	#Return this information to be processed.
	def CollectOutfitInfoDicts(self,lst_params):
		result = urlfetch.fetch(self.str_ps2Outfit_url, payload = urllib.urlencode(self.dict_outfitFields ), deadline = 60,method = urlfetch.POST)

		lst_memberData = []


		if result.status_code == 200:

			self.lst_members = json.loads(result.content)["outfit_list"][0]["members"]

			successful = 0
			failed = False
			#get each member (by name) from the character site. Deadline of 60 seconds.
			#for i in range(1,2):
			for member in self.lst_members:

				failed = False
				try:
					result = urlfetch.fetch(self.str_ps2Char_url , payload = urllib.urlencode({"name.first_lower":member["name"]["first_lower"] }),deadline = 60,method =urlfetch.POST)
				except KeyError:
					logging.info(member)
					failed = True
				finally:

					#logging.info(result.status_code)                
					if result.status_code == 200 and failed == False:
						logging.info(member["name"])
						recDict = json.loads(result.content)
		
		
						try:
		
		
							data = None
							for parItem in lst_params:
								if data == None:
									data = recDict[parItem]
								else:
									data = data[parItem]
							#logging.info(data)
							lst_memberData.append(data)#["character_list"][0]["stats"]["killed_by"])
							successful +=1# if exception not raised count as information gathered
							logging.info(successful)
		
						except KeyError:
							logging.info( "Oh noes! KeyError, no data!")
						except TypeError:
							logging.info( "Oh noes! TypeError, no data!")# Whathefuckery exception, catch it and pretend it didnt happen.
						finally: 
							print "Stuff = happening"


			#logging.info(lst_memberData)
			return lst_memberData